package cn.iocoder.yudao.module.system.mq.consumer;

import cn.iocoder.yudao.framework.mq.redis.core.stream.AbstractRedisStreamMessageListener;
import cn.iocoder.yudao.module.system.mq.message.ReportGenerateMessage;
import cn.iocoder.yudao.module.system.service.ai.UserReportService;
import cn.iocoder.yudao.module.system.controller.admin.ai.vo.UserReportSaveReqVO;
import cn.iocoder.yudao.module.system.util.baidu.TextFomatterUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.ExecutionException;

import static cn.iocoder.yudao.module.system.util.baidu.BaiduAiUtils.APP_BUILDER_TOKEN;

/**
 * 报告生成消费者
 *
 * @author zhaoying
 */
@Component
@Slf4j
public class ReportGenerateConsumer extends AbstractRedisStreamMessageListener<ReportGenerateMessage> {

    @Resource
    private UserReportService userReportService;

    @PostConstruct
    public void init() {
        log.info("[ReportGenerateConsumer][消费者初始化完成] StreamKey: {}, Group: {}",
                getStreamKey(), getGroup());
    }

    @Override
    public void onMessage(ReportGenerateMessage message) {
        long startTime = System.currentTimeMillis();
        log.info("[onMessage][开始处理报告生成消息: userId={}, answerRecordId={}, version={}]",
                message.getUserId(), message.getAnswerRecordId(), message.getVersion());

        try {
            // 设置百度AI Token
            System.setProperty("APPBUILDER_TOKEN", APP_BUILDER_TOKEN);

            // 构建请求对象
            long buildStartTime = System.currentTimeMillis();
            UserReportSaveReqVO userReportSaveReqVO = new UserReportSaveReqVO();
            userReportSaveReqVO.setUserId(message.getUserId());
            userReportSaveReqVO.setAnswerRecordId(message.getAnswerRecordId());
            userReportSaveReqVO.setVersion(message.getVersion());
            userReportSaveReqVO.setName(message.getName());

            // 处理问题内容
            if (!StringUtils.isEmpty(message.getQuestion())) {
                String formattedQuestion = TextFomatterUtils.convertQuestionnaireToTemplateTexts(
                        message.getQuestion(), message.getVersion());
                userReportSaveReqVO.setQuestion(formattedQuestion);
            }

            log.info("[onMessage][请求对象构建完成: userId={}, 耗时={}ms]",
                    message.getUserId(), System.currentTimeMillis() - buildStartTime);

            // 根据版本生成报告
            long serviceStartTime = System.currentTimeMillis();
            if (message.getVersion() == 1) {
                // 专业版
                userReportService.createUserReportBySd(userReportSaveReqVO);
                log.info("[onMessage][专业版报告生成任务已提交: userId={}, answerRecordId={}, 服务调用耗时={}ms]",
                        message.getUserId(), message.getAnswerRecordId(),
                        System.currentTimeMillis() - serviceStartTime);
            } else {
                // 基础版
                try {
                    userReportService.createUserReportByCf(userReportSaveReqVO);
                    log.info("[onMessage][基础版报告生成任务已提交: userId={}, answerRecordId={}, 服务调用耗时={}ms]",
                            message.getUserId(), message.getAnswerRecordId(),
                            System.currentTimeMillis() - serviceStartTime);
                } catch (ExecutionException | InterruptedException e) {
                    log.error("[onMessage][基础版报告生成失败: userId={}, answerRecordId={}, 耗时={}ms]",
                            message.getUserId(), message.getAnswerRecordId(),
                            System.currentTimeMillis() - startTime, e);
                    throw new RuntimeException("报告生成失败", e);
                }
            }

            long totalTime = System.currentTimeMillis() - startTime;
            log.info("[onMessage][报告生成消息处理完成: userId={}, answerRecordId={}, 总耗时={}ms]",
                    message.getUserId(), message.getAnswerRecordId(), totalTime);

        } catch (Exception e) {
            long totalTime = System.currentTimeMillis() - startTime;
            log.error("[onMessage][报告生成消息处理失败: userId={}, answerRecordId={}, 总耗时={}ms]",
                    message.getUserId(), message.getAnswerRecordId(), totalTime, e);
            throw e; // 重新抛出异常，让消息队列进行重试
        }
    }
}
